<template>

  <el-container>
    <!-- <el-header>Header</el-header> -->
    <el-main>
      <!-- <el-card class="box-card"> -->
      <div slot="header" class="pageheader">

        <div style="margin-left: 20px;">
          <div class="block">
            <!-- <el-button  type="success"  >月份</el-button> -->

            <el-date-picker v-model="chooseDate" type="month" placeholder="选择月份" />

            <el-button type="primary" @click="SearchHandle">刷新</el-button>
            <span class="spanMargin"></span>  
            <el-button icon="Plus" type="success" @click="Addhandle">添加</el-button>
            <span class="spanMargin"></span> 
            <el-button :icon="Printer" type="warning" @click="exportCurPage">导出当前</el-button>
            <span class="spanMargin"></span> 
            <el-button :icon="Printer" type="warning" @click="exportYearVisible = true">年汇总</el-button>
            <span> </span>
           
            <!-- <el-button :icon="Printer" type="warning" @click="handlePrint">打印pdf</el-button> -->

          </div>
        </div>

      </div>
      <div class="home">
        <!-- 请求信息 -->

        <!-- 数据列表 -->
        <el-row :gutter="20">
          <el-col :span="24">

            <el-table :data="WorkList" id="out-table" style="width: 100%; " :height="tableHeight" border  stripe
            :cell-style="{ textAlign: 'center' }"   @row-dblclick="handleDblClick" :summary-method="getSummaries" show-summary>

              <!-- <el-table-column fixed type="selection" width="55"> </el-table-column> -->

              <el-table-column prop="RECORD_TIME" fixed="left" :formatter="dateFormatter" label="日期" width="110" />

              <el-table-column label="班次" fixed="left" width="80">
                  <template #default="scope">
                    <el-popover effect="light" trigger="hover" placement="top" width="auto">
                      <template #default>
                        <div>白班: 早8点到晚8点</div>
                        <div>夜班: 当前晚8点到次日早8点</div>
                      </template>
                      <template #reference>
                        <el-tag type="warning" v-if="scope.row.WORKTYPE=='白班'">白班</el-tag>
                        <el-tag v-else="scope.row.WORKTYPE=='白班'">白班</el-tag>
                      </template>
                    </el-popover>
                  </template>
                </el-table-column>

              <!-- <el-table-column prop="WORKTYPE" fixed="left" label="班次" width="80" /> -->

              <el-table-column v-for="(item, index) in ColList" :prop="item.FieldName" width="80">
                <template #header>
                  <div class="headstr">
                    {{ item.Header }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="NURSENAME" fixed="right" label="护士签名" width="110" />

            </el-table>

          </el-col>
        </el-row>

      </div>
      <!-- </el-card> -->

    </el-main>
    <!-- <el-footer>
      <div class="footer-area">

      </div>
    </el-footer> -->
    <!-- <div class="bottomGroup">
    
      <el-row :gutter="20">
        <el-col :span="24">
          <el-button icon="el-icon-s-open" @click="Refresh">刷新</el-button>

        </el-col>
      </el-row>
    </div> -->
  </el-container>
  <!-- 悬浮窗 -->
  <div style="position: fixed; left: 2px; top:20px; z-index: 99;">
    <el-button type="primary" @click="letSeting = true" icon="Edit" circle />
    <!-- <el-button type="primary" link icon="DArrowRight" @click="letSeting = true" /> -->
  </div>

   <!-- 全屏 -->
   <div style="position: fixed; right: 5px; top:5px; z-index: 99;">
   
    <el-button @click="toggleFullScreen" type="default" ><el-icon><FullScreen /></el-icon></el-button>
    <!-- <el-button type="primary" link icon="DArrowRight" @click="letSeting = true" /> -->
  </div>
  <!-- 左侧显示列配置 -->
  <el-drawer size="430" v-model="letSeting" title="操作面板" :with-header="false" direction="ltr">
    <div class="setting">
      <el-row :gutter="5" class="settop">
        <el-button type="default" @click="handleSort" :icon="Sort" plain>{{ !isSort ? '开启排序' : '关闭排序' }}</el-button>
        <el-button type="success" @click="handelSaveSort"  :icon="Sort" plain>保存</el-button>

      </el-row>
      <el-row class="setbootm">
        <el-col>
          <el-table id="newsBannerManagementTable" :data="ALlColList" style="width: 100%; " :height="tableHeight" border  stripe>
            <el-table-column prop="Header" label="列头文本" width="110" />
            <el-table-column prop="FieldName" label="字段名" width="60" />
            <el-table-column prop="Sort" label="排序" width="60" />
            <el-table-column prop="IfShow" label="显示" width="60" />
            <el-table-column align="right" fixed="right" width="80">
              <template #header>
                <div class="headstr">
                  操作
                </div>
              </template>
              <template #default="scope">
                <el-button type="primary" size="small" @click="IfShowhandle(scope.$index, scope.row)">
                  显/隐
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
  </el-drawer>

  <!-- 新增对话框 -->
  <el-dialog v-model="dialogFormVisible" width="95%" title="添加记录">
    <el-form :model="AddModel" label-width="100px" label-position="right">
      <el-row>
        <el-col :span="8">
          <el-form-item label="日期:">
            <el-date-picker :disabled-date="disabledDate" v-model="AddModel.RECORD_TIME" type="date" placeholder="日期" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="班次:">
            <el-select v-model="AddModel.WORKTYPE" placeholder="班次">
              <el-option label="白班" value="白班" />
              <el-option label="夜班" value="夜班" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="护士名:">
            <el-input v-model="AddModel.NURSENAME" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col v-for="(item, index) in ColList" :span="ColSpaceNum">
          <el-form-item :label="item.Header + ':'">
            <el-input v-model="AddModel[item.FieldName]" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="SaveHandle">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 确认年统计 -->
  <el-dialog v-model="exportYearVisible" title="提示" width="500">
    <span>确定要进行年汇总吗？</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="exportYearVisible = false">取消</el-button>
        <el-button type="primary" @click="exportYear">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
import dayjs from "dayjs";
import { enableRowDrop } from "@/util/sortable"
import { ref, watch, onMounted, toRaw, watchEffect } from "vue";
import Sortable from 'sortablejs'
//组件
import { ElMessage, ElNotification } from "element-plus"
//Api
import { GetNurseDayWorksByMouth, GetNurseDayWorkById, SaveNurseDayWork, GetDictCol, SaveDictColSort, GetExcel } from "../util/request"

import { useUserStore } from "@/store/user.js"

const exportYearVisible = ref(false);



const letSeting = ref(false)//左侧设置面板展示
const UserStore = useUserStore();
// 选择月份
const chooseDate = ref(dayjs())
//调整月份，刷新数据
watch(chooseDate, (newValue, oldValue) => {
  if (newValue != oldValue) {
    SearchHandle();
  }
});
// 导出当前页
const exportCurPage = () => {
  //route.meta.title
  let name = '护士工作量统计';

  var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'), { sheet: name, raw: true })
  console.log(wb)
  var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), `${name}.xlsx`)
  } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
  return wbout
}

//年统计
const exportYear = () => {

  exportYearVisible.value = false;
  let years = dayjs(chooseDate.value).format('YYYY');
  let parm = { year: years };

  GetExcel(parm).then((res) => {
    let blob = new Blob([res.data]);
    let url = window.URL.createObjectURL(blob); // 创建 url 并指向 blob
    let a = document.createElement('a');
    a.href = url;
    //获取文件名（不一定能拿到，拿不到就要自定义了）
    let name = years+"年度汇总.xls";
    a.download = name;
    a.click();
    window.URL.revokeObjectURL(url); // 释放该 url 
    showSuccess();
  });
}

// 只能选择本月的日期
const disabledDate = (time) => {
  // 获取当前月份
  let dt1 = dayjs(chooseDate.value).format('YYYY-MM');

  let dt2 = dayjs(time).format('YYYY-MM')
  return dt1 !== dt2
}

//新建弹出框显示隐藏
const dialogFormVisible = ref(false)
//新建按钮
function Addhandle() {
  let data = { "ID": 0, "RECORD_TIME": null, "GROUPNAME": "", "CREATE_TIME": null, "WORKTYPE": "白班", "NURSENAME": "", "C1": "", "C2": "", "C3": "", "C4": "", "C5": "", "C6": "", "C7": "", "C8": "", "C9": "", "C10": "", "C11": "", "C12": "", "C13": "", "C14": "", "C15": "", "C16": "", "C17": "", "C18": "", "C19": "", "C20": "", "C21": null, "C22": null, "C23": null, "C24": null, "C25": null };
  data.RECORD_TIME = chooseDate.value;
  data.DATE_TIME = dayjs()
  AddModel.value = data;
  dialogFormVisible.value = true;
}
//提示成功
const showSuccess = () => {
  ElNotification({
    title: '成功',
    message: '操作成功',
    type: 'success',
  })
}
//提示失败
const showFail = (msg) => {
  ElNotification({
    title: '失败',
    message: msg,
    type: 'error',
  })
}
//---全屏
const isFullScreen = ref(false);
 
const toggleFullScreen = () => {
  if (!document.fullscreenElement) {
    // 进入全屏
    document.documentElement.requestFullscreen();
    isFullScreen.value = true;
  } else {
    // 退出全屏
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
    isFullScreen.value = false;
  }
};

////----拖动

// 排序--当前是否开启排序
const isSort = ref(false)

// 排序--点击开始排序
const handleSort = async () => {
  //listQuery.size = 100
  //await getList()
  isSort.value = true
  // 开启排序
  enableRowDrop(setNewSortArray, ColList.value, true, 'newsBannerManagementTable')
}

// 排序完后的id数组
const realSortIdArray = ref([])

/**
 * 拿到传递过来的数组列表
 * @param sortArray 排序好的id数组
 */
const setNewSortArray = (sortArray) => {
  if (sortArray) {
    realSortIdArray.value = sortArray
  }
}

// 排序--点击保存排序
const handelSaveSort = async () => {
  try {
    let data = realSortIdArray.value;
    console.log(ALlColList.value)
    isSort.value = false
    // 关闭排序
    //enableRowDrop(setNewSortArray, ColList.value, true, 'newsBannerManagementTable');
    if (!data || data.length <= 0) {
      data = ALlColList.value;// = JSON.parse(JSON.stringify(ALlColList.value)) 
    }
    SaveDictColSort(data).then((res) => {
      console.log("操作成功");
      location.reload();
    });
  } catch (e) {
    console.log('🚀 排序出错:', e)
  }
  realSortIdArray.value = [];
}

//切换显示隐藏
function IfShowhandle(i, b) {
  // 取出原始对象

  console.log(b.IfShow);
  b.IfShow = b.IfShow == '是' ? "否" : "是";

}

//---拖动完毕
//添加实体
const AddModel = ref({});
//列表
const WorkList = ref([]);
//点击打印
function handlePrint() {
  let dt1 = dayjs(chooseDate.value).format('YYYY-MM');
  let url2 = '/api/Print/PrintPdf?id=ONE|' + dt1;
  window.open(url2, '_self');

}

//点击搜索
function SearchHandle() {

  let dt = dayjs(chooseDate.value).format('YYYY-MM');
  console.log(dt);
  var parm = { mouth: dt };
  console.log(parm)
  GetNurseDayWorksByMouth(parm).then((res) => {
    console.log("查询成功");
    WorkList.value = res;
  });
}


const ColSpaceNum = ref(6);

//获取列配置
const ColList = ref([]);
//所有包含隐藏
const ALlColList = ref([]);
function GetColList() {
  var parm = {};
  GetDictCol(parm).then((res) => {

    ColList.value = res.filter(c => {
      return c.IfShow == '是';
    })
    ALlColList.value = res;
  }).catch(() => {

  }).finally(() => {

  });

}

//保存
function SaveHandle() {
  const pdata = toRaw(AddModel.value);

  if (pdata.RECORD_TIME instanceof Object) {
    //添加日期转字符串
    pdata.RECORD_TIME = dayjs(pdata.RECORD_TIME).format('YYYY-MM-DD');
    console.log(pdata.RECORD_TIME);
  }

  SaveNurseDayWork(pdata).then((res) => {
    console.log(res)
    showSuccess();
    dialogFormVisible.value = false;
    SearchHandle();
  }).catch((error) => {

  });
}

//双击
function handleDblClick(row, column, event) {
  console.log(row.ID);
  var parm = { id: row.ID };
  GetNurseDayWorkById(parm).then((res) => {
    console.log("查询单条");
    AddModel.value = res;
    //弹出修改界面
    dialogFormVisible.value = true;
  });
}
//合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
 
    switch (column.property)
    {
      case "NURSENAME":
      case "WORKTYPE":
      sums[index] = ''
      return;
      case "RECORD_TIME":
      sums[index] = '合计:'
      return;
    }
     
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)}`
    } else {
      sums[index] = ''
    }

  })

  return sums
}
const tableHeight = ref(800);
//获取表格高度
const getTableHeight = () => {
  const tableH = 90; //距离页面下方的高度
  const tableHeightDetil = window.innerHeight - tableH;
  if (tableHeightDetil <= 300) {
    tableHeight.value = 300;
  } else {
    tableHeight.value = window.innerHeight - tableH;
  }
};

// 监听窗口变化动态设置表格高度
window.onresize = () => {
  getTableHeight()
}

function dateFormatter(row, column) {

  let datetime = row.RECORD_TIME;
  if (datetime) {
    return dayjs(datetime).format('YYYY-MM-DD');
  }
  return ''
}


//挂载完毕
onMounted(() => {

  console.log('登录信息')
  console.log(UserStore.data)

  getTableHeight()
  // watchEffect(() => {
  //   const windowHeight = window.innerHeight;
  //   // 这里可以执行你需要的操作，比如更新数据或者调用方法
  //   console.log(`屏幕高度变化了，现在是：${windowHeight}px`);
  // });

  if (window.innerWidth <= 568)
    ColSpaceNum.value = 24
  if (window.innerWidth <= 912)
    ColSpaceNum.value = 12
  else if (window.innerWidth <= 1024)
    ColSpaceNum.value = 8
  else if (window.innerWidth <= 1624)
    ColSpaceNum.value = 6
  GetColList();
  //当天日期
  let dtStr = dayjs().format('YYYY-MM');
  let df = dayjs(dtStr);
  chooseDate.value = df;

})

</script>

<style scoped lang="scss">
.pageheader {
  display: flex;
  flex-direction: row;
  justify-items: flex-start;
  vertical-align: middle;
  align-items: center;
}

.bottomGroup {
  position: fixed;
  z-index: 999;
  bottom: 0px;
  left: 0px;
  width: 100%;
  overflow: hidden;
  background-color: grey;
  color: white;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  height: 60px;
  padding: 20px;
  margin: 0px 2px;
  box-sizing: border-box;
}

.footer-area {
  height: 10px;
}

.box-card {
  padding: 0px;
  margin: 0px;
}

.headstr {
  text-align: center;
}


/* 左侧设置面板布局 */
.setting {
  position: relative;

}

.settop {
  position: fixed;
  padding: 10px;
  background-color: white;
  left: 0px;
  top: 0px;
  z-index: 2;
}

.setbootm {
  margin-top: 30px;
}


.spanMargin{
  padding: 5px;
}
</style>